import time
import random
from machine import SPI, Pin
import st7735_buf  # 彩屏驱动模块
from lib.easydisplay import EasyDisplay    # 易用显示屏类
from lib.easymenu import EasyMenu, MenuItem, ValueItem    # 易用菜单相关类

# 导入游戏库
from game.game_rps import run as game_rps
from game.game_breakout import run as game_breakout
from game.game_snake import run as game_snake
from game.game_tetris import run as game_tetris

# 初始化显示屏
spi = SPI(2, baudrate=20000000, polarity=0, phase=0, sck=Pin(18), mosi=Pin(23))  # 初始化 SPI 通信
dp = st7735_buf.ST7735(
    width=160, height=128, spi=spi, cs=5, dc=4, res=19, rotate=1, bl=None, invert=False, rgb=False  # 初始化屏幕驱动
)
ed = EasyDisplay(  # 初始化 EasyDisplay 对象，用于简化显示操作
    display=dp, font="/font/text_lite_16px_2312.v3.bmf", show=True, color=0xFFFF, auto_wrap=True, color_type="RGB565"
)

# 初始化按钮，使用内部上拉电阻
k_u = Pin(2, Pin.IN, Pin.PULL_UP)   # 上键
k_d = Pin(13, Pin.IN, Pin.PULL_UP)  # 下键
k_l = Pin(27, Pin.IN, Pin.PULL_UP)  # 左键
k_r = Pin(35, Pin.IN, Pin.PULL_UP)  # 右键
k_a = Pin(34, Pin.IN, Pin.PULL_UP)  # A 键
k_b = Pin(12, Pin.IN, Pin.PULL_UP)  # B 键

# 主菜单项
menu = MenuItem(  # 主菜单的标题
    title=('ESP32 游戏机', 'c', 0), layout=[1, 4], spacing=[160, 16]  # 设置菜单布局和间距
)



# 将游戏添加到主菜单
menu.add(ValueItem('石头剪刀布', callback=lambda: game_rps(ed, k_u, k_d, k_l, k_a, k_b)))
menu.add(ValueItem('打砖块', callback=lambda: game_breakout(ed, k_u, k_d, k_l, k_r, k_a, k_b)))
menu.add(ValueItem('贪吃蛇', callback=lambda: game_snake(ed, k_u, k_d, k_l, k_r, k_a, k_b)))
menu.add(ValueItem('俄罗斯方块', callback=lambda: game_tetris(ed, k_u, k_d, k_l, k_r, k_a, k_b, dp)))

# 创建 EasyMenu 对象
em = EasyMenu(ed, menu)

# 按键回调函数
def k_u_down():
    em.prev()  # 上键：上一项

def k_d_down():
    em.next()  # 下键：下一项

def k_a_down():
    em.click()  # A 键：确认

def k_b_down():
    em.back()  # B 键：返回

# 显示菜单
em.show()

# 主循环
while True:
    if k_u.value() == 0:  # 按下上键
        k_u_down()
    elif k_d.value() == 0:  # 按下下键
        k_d_down()
    elif k_a.value() == 0:  # 按下 A 键
        k_a_down()
    elif k_b.value() == 0:  # 按下 B 键
        k_b_down()

